package com.example.shardingjdbctest.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.example.shardingjdbctest.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class TestController {
    private  ThreadLocal<Integer> count = new ThreadLocal<>();
    @Resource
    UserMapper userMapper;

    /**
     * 如果是主键自动生成的，切记不要传入id，否则会报错
     */
    @GetMapping("/add")
    public Object add() {
        if(count.get()==null){
            count.set(1);
        }
        count.set(count.get().intValue()+1);
        System.out.println(Thread.currentThread().getName()+"=============================="+count.get());
       return "ok";
    }


    @GetMapping("/list")
    public Object list() {

        return userMapper.selectAll();
    }


    @GetMapping("/like")
    public Object like() {

        return userMapper.selectLike("%2%");
    }

    @GetMapping("/page")
    public Object page() {

        return userMapper.selectLikePage("%2%");
    }

    @GetMapping("/limitQuery")
    public Object limitQuery() {
        return userMapper.limitQuery(80);
    }

    //nacos服务配置
    @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
    private boolean useLocalCache;

    @RequestMapping(value = "/get", method = GET)
    @ResponseBody
    public boolean get() {
        return useLocalCache;
    }

    //启动服务发现
    @NacosInjected
    private NamingService namingService;

    @RequestMapping(value = "/discovery/get", method = GET)
    @ResponseBody
    public List<Instance> get(@RequestParam String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }
}